package com.guohao.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guohao.reggie.common.BaseContext;
import com.guohao.reggie.common.CustomException;
import com.guohao.reggie.entity.*;
import com.guohao.reggie.mapper.OrderMapper;
import com.guohao.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingService shoppingService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    // 用户下单
    @Override
    public void submit(Orders orders) {

        //1. 获得当前用户Id, 查询当前用户购物车数据
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCartList = shoppingService.list(shoppingCartLambdaQueryWrapper);// 用户购物车数据

        if (shoppingCartList == null || shoppingCartList.size() == 0){
            throw new CustomException("购物车为空 不能下单!");
        }
        //2. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(currentId);


        //3. 根据地址ID, 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBookId == null ){
            throw new CustomException("地址信息有误 不能下单!");
        }

        long orderId = IdWorker.getId();//订单号 雪花算法

        AtomicInteger amount = new AtomicInteger(0);  //总价格
        //4. 组装订单明细数据, 批量保存订单明细

        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //5. 组装订单数据, 批量保存订单数据

        orders.setId(orderId); // 订单ID
        orders.setOrderTime(LocalDateTime.now()); // 创建实际
        orders.setCheckoutTime(LocalDateTime.now()); // 结账时间
        orders.setStatus(2); // 状态
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(currentId); //用户id
        orders.setNumber(String.valueOf(orderId)); // 订单号
        orders.setUserName(user.getName()); // 用户名
        orders.setConsignee(addressBook.getConsignee()); // 收货人
        orders.setPhone(addressBook.getPhone()); // 收货人 电话
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        // 订单表插入数据, 一条
        this.save(orders);

        // 订单明细表插入数据 多条
        orderDetailService.saveBatch(orderDetails);

        //6. 删除当前用户的购物车列表数据
        shoppingService.remove(shoppingCartLambdaQueryWrapper);

    }
}
